﻿using LY.Common.Utils.InterestAmt;
using LY.DataAccess.Repository;
using LY.Entity;
using LY.Entity.Entities;
using LY.Entity.PageSearch;
using LY.Entity.SearchEntity;
using LY.Interface;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Transactions;

namespace LY.Business.ServiceImpl
{
    public class T_ProjectService : IT_ProjectService
    {
        T_ProjectRepository _repo;
        ScoreRepository _srepo;
        public T_ProjectService()
        {
            _repo = new T_ProjectRepository();
            _srepo = new ScoreRepository();
        }
        public PagedList<T_Investment_EX> QueryInvestmentList(int? projectid, int? status, ProjectSearch search, PageView view)
        {
            return _repo.QueryInvestmentList(projectid, status, search, view);
        }

        /// <summary>
        /// 获取债权列表
        /// </summary>
        /// <param name="search"></param>
        /// <param name="view"></param>
        /// <returns></returns>
        public PagedList<T_Project_EX> QueryProjectList(T_ProjectSearch search, PageView view)
        {
            return _repo.QueryProjectList(search, view);
        }
        //查询子项目列表？
        public PagedList<T_Project> QueryProjectList(int? id, ProjectSearch search, PageView view)
        {
            return _repo.QueryProjectList(id, search, view);
        }

        public PagedList<U_Company> QueryCompany_EXList(CompanySearch search, PageView view)
        {
            return _repo.QueryCompanyList(search, view);
        }

        public PagedList<T_Project> QueryProjectListPage(PageView view, int pageSize, int? currentPage)
        {
            return _repo.QueryProjectListPage(view, pageSize, currentPage);
        }
        public List<T_Project> GetProjectList()
        {
            return _repo.GetProjectList();
        }

        public List<T_Project> GetProjectList(int? id)
        {
            return _repo.GetProjectList(id);
        }

        public List<T_RelevantDocument> GetRelevantList(int? id)
        {
            return _repo.GetRelevantList(id);
        }
        /// <summary>
        /// 最新投资项目
        /// </summary>
        /// <returns></returns>
        public List<T_Project_EX> GetNewProjectList(string isNewProject, int top)
        {
            return _repo.GetNewProjectList(isNewProject, top);
        }
        public string GetProjectNo()
        {
            return "";
        }

        public string RepaymentPlanNO()
        {
            return _repo.RepaymentPlanNO();
        }

        public int SaveRepaymentPlan(int? id, string RepaymentPlanNO, double? CurrentPrincipal, decimal? TotalLoan)
        {
            return _repo.SaveRepaymentPlan(id, RepaymentPlanNO, CurrentPrincipal, TotalLoan);
        }

        public double getRemainingPrincipal(int? id)
        {
            return _repo.getRemainingPrincipal(id);
        }

        public int GetRepmStatus(int? id)
        {
            return _repo.GetRepmStatus(id);
        }

        public PagedList<T_RepaymentPlan_EX> QueryRepaymentPlanList(ProjectSearch search, PageView view)
        {
            return _repo.QueryRepaymentPlanList(search, view);
        }

        public PagedList<T_RepaymentPlan_EX> QueryToBeRepaymentPlanList(ProjectSearch search, PageView view)
        {
            return _repo.QueryToBeRepaymentPlanList(search, view);
        }

        public PagedList<T_RepaymentPlan_EX> QueryToBeRepaymentDetailList(ProjectSearch search, PageView view)
        {
            return _repo.QueryToBeRepaymentPlanList(search, view);
        }
        public PagedList<T_RepaymentPlan_EX> QueryRepaymentPlanList(int? id, ProjectSearch search, PageView view)
        {
            return _repo.QueryRepaymentPlanList(id, search, view);
        }
        public int RepaymentPlan(int? id)
        {
            return _repo.RepaymentPlan(id);
        }

        public int ChangeLoan(int? id, string name)
        {
            return _repo.ChangeLoan(id, name);
        }

        public int ChangeAudit(int? id, string name, int? status, string Audit)
        {
            return _repo.ChangeAudit(id, name, status, Audit);
        }

        public int ChangeRept(int? id, string name)
        {
            return _repo.ChangeRept(id, name);
        }

        public List<T_FundsFlow> getFundsList(int? id)
        {
            return _repo.getFundsList(id);
        }

        public int SaveRept(int? projectid, string name, int? id, int? MemberId, double? OutPay)
        {
            return _repo.SaveRept(projectid, name, id, MemberId, OutPay);
        }



        /// <summary>
        /// 获取项目列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="projectTime"></param>
        /// <param name="AnnualisedRates"></param>
        /// <param name="RepaymentStatus"></param>
        /// <param name="projectStatus"></param>
        /// <returns></returns>
        public List<T_Project_EX> GetProjectListNew(int? pageIndex, int pageSize, string projectTime, string AnnualisedRates, string projectStatus)
        {
            return _repo.GetProjectListNew(pageIndex, pageSize, projectTime, AnnualisedRates, projectStatus);
        }

        /// <summary>
        /// 获取项目总数
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="projectTime"></param>
        /// <param name="AnnualisedRates"></param>
        /// <param name="RepaymentStatus"></param>
        /// <param name="projectStatus"></param>
        /// <returns></returns>
        public int GetProjectListNewCount(int? pageIndex, int pageSize, string projectTime, string AnnualisedRates, string projectStatus)
        {
            return _repo.GetProjectListNewCount(pageIndex, pageSize, projectTime, AnnualisedRates, projectStatus);
        }

        public List<T_WindControlInformation> GetWindList(int? id)
        {
            return _repo.GetWindList(id);
        }

        /// <summary>
        /// 新增 编辑项目信息
        /// </summary>
        /// <param name="project"></param>
        /// <param name="windconinfo"></param>
        /// <param name="relement"></param>
        /// <param name="eFPhotoPaths"></param>
        /// <param name="eFPhotoExplain"></param>
        /// <returns></returns>
        public int SaveProject(T_Project project, T_WindControlInformation windconinfo, T_RelevantDocument relement, string eFPhotoPaths, string eFPhotoExplain)
        {
            int ret = -1;
            using (TransactionScope scope = new TransactionScope())
            {
                if (project.ID <= 0)
                {
                    //新增
                    int proId = (int)_repo.Insert(project);
                    windconinfo.ProjectID = proId;
                    relement.ProjectID = proId;
                    _repo.Insert(windconinfo);
                    if (!string.IsNullOrEmpty(eFPhotoPaths))
                    {
                        //删除
                        _repo.DeleteRelementByPid(proId);
                        string[] arr = eFPhotoPaths.Split(',');
                        for (int i = 0; i < arr.Length; i++)
                        {
                            string[] graphs = arr[i].Split('/');
                            relement.EFPhotographs = graphs[1];
                            relement.EFPhotoExplain = eFPhotoExplain.Split(',')[i];
                            relement.EFPhotoPath = "/FileUpload/" + graphs[2] + "/" + graphs[1];
                            relement.TitlePic = graphs[0];
                            _repo.Insert(relement);
                        }
                    }
                    ret = proId;
                }
                else
                {
                    //编辑
                    _repo.Update(project);
                    windconinfo.ProjectID = project.ID;
                    relement.ProjectID = project.ID;
                    _repo.Update(windconinfo);
                    //_repo.Update(relement);
                    //删除
                    _repo.DeleteRelementByPid(project.ID);
                    if (!string.IsNullOrEmpty(eFPhotoPaths))
                    {
                        string[] arr = eFPhotoPaths.Split(',');
                        for (int i = 0; i < arr.Length; i++)
                        {
                            string[] graphs = arr[i].Split('/');
                            relement.EFPhotographs = graphs[1];
                            relement.EFPhotoExplain = eFPhotoExplain.Split(',')[i];
                            relement.EFPhotoPath = "/FileUpload/" + graphs[2] + "/" + graphs[1];
                            relement.TitlePic = graphs[0];
                            _repo.Insert(relement);
                        }
                    }

                    ret = 1;
                }
                scope.Complete();   //提交

            }

            return ret;

        }

        public int SaveProject(T_Project_EX project)
        {
            if (project.ID <= 0)
            {
                //新增
                return (int)_repo.Insert(project);
            }
            else
            {
                //编辑
                return (int)_repo.Update(project);
            }

        }

        public int SaveRelement(int? id, string filePathName, string name, string ename, string filePath)
        {
            int ret = -1;
            using (TransactionScope scope = new TransactionScope())
            {
                T_RelevantDocument relement = new T_RelevantDocument();
                relement.EFPhotographs = filePathName;
                relement.EFPhotoPath = filePath;
                relement.TitlePic = name;
                relement.EFPhotoExplain = ename;
                relement.ProjectID = id;
                _repo.Insert(relement);
                scope.Complete();   //提交
                ret = 1;
            }

            return ret;
        }

        /// <summary>
        /// 删除项目信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int DeleteProject(int id)
        {
            return _repo.DeleteProject(id);
        }

        /// <summary>
        /// 保存会员投资信息
        /// </summary>
        /// <param name="inves"></param>
        /// <returns></returns>
        public int SaveInvestment(T_Investment inves)
        {
            if (inves.Id <= 0)
            {
                //新增
                return (int)_repo.Insert(inves);
            }
            else
            {
                //编辑
                return (int)_repo.Update(inves);
            }
        }
        /// <summary>
        /// 删除会员投资信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int DeleteInvestment(int id)
        {
            return _repo.DeleteInvestment(id);
        }

        public int DeleteRelement(int id)
        {
            return _repo.DeleteRelement(id);
        }

        /// <summary>
        /// 检索投资信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public T_Investment GetInvesment(int? id)
        {
            return _repo.GetInvesment(id);
        }

        public T_Project_EX GetProject_EXByID(int? id)
        {
            return _repo.GetProject_EXByID(id);
        }

        /// <summary>
        /// 获取项目信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public T_Project_EX GetProject(int? id)
        {
            return _repo.GetProject(id);
        }

        //我要投标
        public int ImmedBidSave(T_Investment investment)
        {
            int ret = -1;
            using (TransactionScope scope = new TransactionScope())
            {
                DateTime now = DateTime.Now;
                //T_FundsFlow funds = new T_FundsFlow()
                //{
                //    OrderNo="HJH" + now.ToString("yyMMddhhmmss")+new Random().Next(10000,99999).ToString(),
                //    MemberId = investment.MemberId,
                //    OutPay = investment.TenderAmt,
                //    BankId = 0,
                //    BankName = "",
                //    Balance = 0,
                //    CreateTime = now,
                //    CreateUser = investment.CreateUser,
                //    Status = investment.Status,
                //    Type = 3,
                //    ProjectId = investment.ProjectId
                //};

                //项目信息
                T_Project project = _repo.GetProject(investment.ProjectId);

                //投资年化利率 原+附加利率
                investment.AnnualisedRates = project.AnnualisedRates;
                investment.AddAnnualisedRates = project.AddAnnualisedRates;
                //投资记录
                _repo.Insert(investment);
                //资金记录
                //_repo.Insert(funds);




                int day = 0;
                if (project.DurationMonthOrDay == 1)
                {
                    //月份
                    day = int.Parse(project.ProjectDuration.ToString()) * 30;
                }
                else
                {
                    //天数
                    day = int.Parse(project.ProjectDuration.ToString());
                }
                //添加积分
                U_Score tscore = new U_Score();
                tscore.MemberId = investment.MemberId;
                tscore.InCome = InterestHelper.GetTenderIntegral(investment.TenderAmt, day);
                tscore.OutPay = 0;
                tscore.Balance = 0;
                tscore.CreateTime = now;
                tscore.CreateUser = investment.CreateUser;
                tscore.ProjectId = investment.ProjectId;
                tscore.Type = 5;//投资获得积分
                _srepo.InsertScore(tscore);

                //如果投资金额已满 开始统计项目收益
                T_Investment_EX inves = _repo.GetInvesmentAmt(investment.ProjectId);
                if (inves != null)
                {
                    //剩余可投资金额==0 生成项目收益日期
                    if (inves.BalanceTenderAmt == 0)
                    {
                        DateTime dtNow = DateTime.Now;
                        //修改项目为满标状态
                        project.TenderStatus = 1;
                        //满标时间
                        project.TenderTime = dtNow;
                        _repo.Update(project);
                        //项目还款计划列表
                        List<T_RepaymentPlan_EX> RepPlanList = _repo.QueryRepPlanList(investment.ProjectId);

                        DateTime repPlanDate = dtNow.AddDays(1);
                        int status = 1;
                        for (int i = 0; i < RepPlanList.Count; i++)
                        {
                            if (i == 0)
                            {
                                status = 2;
                            }
                            if (project.DurationMonthOrDay == 1)
                            {
                                //月份
                                //生成项目收益日期
                                _repo.UpdateRepPlanDate(RepPlanList[i].ID, repPlanDate.AddMonths(i + 1), status);
                            }
                            else if (project.DurationMonthOrDay == 2)
                            {
                                //天数
                                repPlanDate.AddDays((int)project.ProjectDuration);
                                _repo.UpdateRepPlanDate(RepPlanList[i].ID, repPlanDate.AddDays((int)project.ProjectDuration), status);
                            }
                        }

                        //更新项目状态为 已投满
                        _repo.UpdateProTendStatus(investment.ProjectId);
                    }
                }

                scope.Complete();
                ret = 1;
            }
            return ret;
        }

        //项目已投金额
        public T_Investment_EX GetInvesmentAmt(int? projectId)
        {
            return _repo.GetInvesmentAmt(projectId);
        }

        //根据projectNo查询这个标的Id
        public int SelectIdByProjectNo(string projectNo)
        {
            return _repo.SelectIdByProjectNo(projectNo);
        }

        //根据T_RepaymentPlan 表的Id 查询出剩余的金额，是否要还本金
        public T_RepaymentPlan_EX GetRepaymentPlanById(int id)
        {
            return _repo.GetRepaymentPlanById(id);
        }

        //在盛付通接口返回成功之后才存储资金记录
        public long CunChuZiJin(T_FundsFlow funds)
        {
            return _repo.Insert(funds);
        }

        //查询出子项目集合
        public List<T_Project> QueryChildProjectList(int parentProjectId)
        {
            return _repo.QueryChildProjectList(parentProjectId);
        }

        //查询一个实体对象
        public T_Project GetModel(int id)
        {
            return _repo.GetModel(id);
        }

        public int SaveModel(T_Project model)
        {
            if (model.ID <= 0)
            {
                return (int)_repo.Insert(model);
            }
            else
            {
                return _repo.Update(model);
            }
        }


        public List<T_RepaymentPlan_EX> QueryRepaymentPlanList(int projectId)
        {
            return _repo.QueryRepaymentPlanList(projectId);
        }


        public int UpdateRepaymentPlanDate(int id, DateTime planDate, int status)
        {
            return _repo.UpdateRepaymentPlanDate(id, planDate, status);
        }


        public PagedList<U_Company> QueryCompanyList(CompanySearch search, PageView view)
        {
            throw new NotImplementedException();
        }



        //获取还款实体对象
        public T_RepaymentPlan GetRepaymentPlan(int projectId)
        {
            return _repo.GetRepaymentPlan(projectId);
        }
        //回款计划
        public List<T_RepaymentPlan_EX> GetRPListByProID(int id)
        {
            return _repo.GetRPListByProID(id);
        }


        public T_Project GetModelByProjectNo(string projectNo)
        {
            return _repo.GetModelByProjectNo(projectNo);
        }



        public int UpdateRepPlanDate(int id, DateTime planDate, int status)
        {
            return _repo.UpdateRepaymentPlanDate(id, planDate, status);
        }


        public PagedList<T_Project_EX> QueryOverFlowProjectList(ProjectSearch search, PageView view)
        {
            return _repo.QueryOverFlowProjectList(search, view);
        }

        //生成项目标号
        public string CreadteProjectNo(T_Project project)
        {
            int myloanType = (int)project.LoanType;
            string oldProjectNo = _repo.GetProjectNo(myloanType);
            string newProjectNo = "";
            if (string.IsNullOrEmpty(oldProjectNo))
            {
                switch (myloanType)
                {
                    case 0:
                        newProjectNo = "QJZQH" + DateTime.Now.ToString("yyyyMMdd") + "0001";
                        break;
                    case 1:
                        newProjectNo = "QJZQC" + DateTime.Now.ToString("yyyyMMdd") + "0001";
                        break;
                    case 2:
                        newProjectNo = "QJZQN" + DateTime.Now.ToString("yyyyMMdd") + "0001";
                        break;
                }
            }
            else
            {
                string LYdate = oldProjectNo.Substring(0, 13);
                int no = int.Parse(oldProjectNo.Substring(oldProjectNo.Length - 4, 4));
                no = no + 1;
                newProjectNo = LYdate + (no).ToString("0000");
                //if (no > 0 && no < 10)
                //{
                //    no++;
                //    if (no != 10)
                //    {
                //        project.ProjectNo = LYdate + "000" + no;
                //    }
                //    else
                //    {
                //        project.ProjectNo = LYdate + "00" + no;
                //    }
                //}
                //else if (no >= 10 && no <= 99)
                //{
                //    no++;
                //    if (no != 100)
                //    {
                //        project.ProjectNo = LYdate + "00" + no;
                //    }
                //    else
                //    {
                //        project.ProjectNo = LYdate + "0" + no;
                //    }
                //}
                //else if (no >= 100 && no <= 999)
                //{
                //    no++;
                //    if (no != 1000)
                //    {
                //        project.ProjectNo = LYdate + "0" + no;
                //    }
                //    else
                //    {
                //        project.ProjectNo = LYdate + no;
                //    }
                //}
                //else
                //{
                //    project.ProjectNo = LYdate + no;
                //}

            }
            return newProjectNo;
        }



    }
}
